from api.models import User, Role, RelationUserRole
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
import json
import hashlib
import jwt
from django.utils import timezone
from aiops_backend import settings
from uniforms.response import Response


@csrf_exempt
@require_POST
def query_login_data(request):
    try:
        # 获取原始请求体数据
        raw_data = request.body
        # 解析Json数据
        data = json.loads(raw_data)
        username = data.get("username")  # 获取用户名
        password = data.get("password")  # 获取密码

        md5 = hashlib.md5()
        md5.update(password.encode())
        md5_password = md5.hexdigest()
        user = User.objects.get(username=username)
        if str(user.password) == str(md5_password):
            token = jwt.encode(
                {
                    "exp": timezone.datetime.now() + timezone.timedelta(days=1),
                    "iat": timezone.datetime.now(),
                    "data": {"id": user.id},
                },
                settings.SECRET_KEY,
                algorithm="HS256",
            )  # 用户名和密码验证成功, 生成token
            return Response.success(data={"token": token})
        else:
            return Response.bad_request(
                "username or password is invalid"
            )  # 密码验证失败
    except Exception as e:
        print(repr(e))
        return Response.bad_request(f"username or password is invalid")


@csrf_exempt
@require_GET
def query_info_data(request):
    try:
        user = request.user
        res = {}
        own_roles = []
        role_ids = RelationUserRole.objects.filter(user_id=user.id).values_list(
            "role_id"
        )
        for role_id in role_ids:
            code = Role.objects.filter(id=role_id[0]).first().code
            own_roles.append(code)
        res = {
            "id": user.id,
            "name": user.username,
            "phone": user.phone,
            "email": user.email,
            "password": user.password,
            "department": user.department,
            "createTime": str(user.create_time.replace(tzinfo=None)),
            "lastEditTime": str(user.last_edit_time.replace(tzinfo=None)),
            "description": user.description,
            "ownRoles": own_roles,
        }
        return Response.success(data=res)
    except Exception as e:
        return Response.bad_request(f"{str(e)}")


@csrf_exempt
@require_POST
def query_logout_data(request):
    return Response.success()
